package com.xwtec.proxy.v6;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Random;

/**
 * @Author: zt
 * @Date: 2021/3/2 22:51
 *
 * jdk 动态代理
 */
public class Tank implements Movable{

    @Override
    public int move() {

        System.out.println("Tank Move claclacla.....");
        try {
            Thread.sleep(new Random().nextInt(4000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return 1;
    }

    public static void main(String[] args) {

        final Tank tank = new Tank();

        System.getProperties().put("jdk.proxy.ProxyGenerator.saveGeneratedFiles","true");

        Movable m = (Movable)Proxy.newProxyInstance(Tank.class.getClassLoader(), new Class[]{Movable.class}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("Tank move start....");
                Object o = method.invoke(tank, args);
                System.out.println("stopped");
                return o;

            }
        });
        System.out.println(m.move());
    }
}

interface Movable{
    int move();
}
